<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of MySQL
 *
 * @author riemerb
 */
class MySQL {

    private $result;
    
    private $conId = null;

    public function __construct() {

        // connect to MySQL and select database
        if (!$this->conId = mysql_connect(Constants::DB_HOST, Constants::DB_BENUTZER, Constants::DB_PASSWORT)) {

            throw new Exception('Error connecting to the server');
        }

        if (!mysql_select_dbi(Constants::DB_NAME, $this->conId)) {

            throw new Exception('Error selecting database');
        }
    }

// run SQL query

    public function query($query) {

        if (!$this->result = mysql_query($query)) {

            $this->closeConnection();
            throw new Exception('Error performing query ' . $query);
        }
    }

// fetch one row
    public function fetchRow() {

        while ($row = mysql_fetch_array($this->result)) {

            return $row;
        }

        return false;
    }
    
    /**
     *Close the Database Connection 
     */
    public function closeConnection() {
        mysqli_close($this->conId);
    }

// fetch all rows

    public function fetchAll($table = 'default_table') {

        $this->query('SELECT * FROM ' . $table);

        $rows = array();

        while ($row = $this->fetchRow()) {

            $rows[] = $row;
        }

        return $rows;
    }

// insert row

    public function insert($params = array(), $table = 'default_table') {

        $sql = 'INSERT INTO '.$table.' ('.implode(',', array_keys($params)).') VALUES ('.implode(', ',array_values($params)).')';

        $this->query($sql);
    }

}
?>



